class_name MonsterDetection
extends HComponent

## Monster检测组件
## 负责检测与玩家的碰撞并触发游戏暂停
## 遵循单一职责原则：只处理碰撞检测和游戏暂停逻辑

# 射线检测相关
var detection_raycast: RayCast3D = null
@export var detection_distance: float = 1.5   # 检测距离
var is_initialized: bool = false

## 组件初始化
func _ready():
	call_deferred("_setup_detection_raycast")

## 设置检测射线
func _setup_detection_raycast():
	if not attach_node:
		print("警告：Monster检测组件未绑定到节点")
		return
	
	# 创建射线检测节点
	detection_raycast = RayCast3D.new()
	detection_raycast.name = "PlayerDetectionRay"
	detection_raycast.target_position = Vector3(0, 0, -detection_distance)
	detection_raycast.enabled = true
	
	# 设置碰撞层级（只检测玩家）
	detection_raycast.collision_mask = 1  # 假设玩家在第1层
	
	# 排除自身碰撞
	if attach_node is RigidBody3D:
		detection_raycast.add_exception(attach_node)
	
	# 添加到monster节点
	attach_node.add_child(detection_raycast)

## 物理更新检测
func _physics_process(_delta):
	_check_player_collision()

## 检测玩家碰撞
func _check_player_collision():
	if not detection_raycast or not detection_raycast.enabled:
		return
	
	# 强制更新射线检测
	detection_raycast.force_raycast_update()
	
	# 检查是否碰到玩家
	if detection_raycast.is_colliding():
		var collider = detection_raycast.get_collider()
		if _is_player_node(collider):
			_on_player_detected()

## 判断碰撞对象是否为玩家
## @param node: 碰撞节点
## @return bool: 是否为玩家节点
func _is_player_node(node: Node) -> bool:
	if not node:
		return false
	
	# 检查节点是否在玩家组中
	if node.is_in_group("player"):
		return true
	
	# 检查是否为已知的玩家节点
	if DataManager.has_method("get_player"):
		var player = DataManager.get_player()
		if player and node == player:
			return true
	
	return false

## 检测到玩家时的处理
func _on_player_detected():
	print("Monster检测到玩家，游戏暂停")
	_pause_game()

## 暂停游戏
func _pause_game():
	# 设置游戏为暂停状态
	#get_tree().paused = true
	
	# 可以在这里添加UI提示等
	print("游戏已暂停 - Monster捕获了玩家")

## 设置检测距离
## @param distance: 新的检测距离
func set_detection_distance(distance: float):
	detection_distance = distance
	if detection_raycast:
		detection_raycast.target_position = Vector3(0, 0, -detection_distance)
